package com.wkbb.sports.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.BeanUtil;
import com.wkbb.common.utils.TimeUtil;
import com.wkbb.sports.dto.*;
import com.wkbb.sports.mapper.HlifeCourseMapper;
import com.wkbb.sports.mapper.HlifeTeachPlanDetailMapper;
import com.wkbb.sports.mapper.HlifeTrainMapper;
import com.wkbb.sports.mapper.HlifeTrainStudentMapper;
import com.wkbb.sports.model.HlifeTeachCourse;
import com.wkbb.sports.model.HlifeTeachCourseAttend;
import com.wkbb.sports.model.HlifeTeachPlanDetail;
import com.wkbb.sports.model.HlifeTrain;
import com.wkbb.sports.service.CourseService;
import com.wkbb.sports.service.DetectService;
import com.wkbb.sports.service.TeachFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CourseServiceImpl implements CourseService {
	
	@Autowired
	private HlifeCourseMapper courseMapper;
	@Autowired
	private DetectService detectService;
	@Autowired
	private TeachFileService teachFileService;
	@Autowired
	private HlifeTrainMapper trainMapper;
	@Autowired
	private HlifeTrainStudentMapper trainStudentMapper;
	@Autowired
	HlifeTeachPlanDetailMapper hlifeTeachPlanDetailMapper;
	@Autowired
	private RedisTemplateUtil redisTemplateUtil;

	@Override
	@Transactional(readOnly=true)
	public PageInfo<StuCourseDto> getStuCoursePageList(Map<String, Object> map, int pageNo, int pageSize)throws Exception  {
		Page<StuCourseDto> page = PageHelper.startPage(pageNo, pageSize, true);
		List<StuCourseDto> list = courseMapper.getStuCoursePageList(map);
		for (StuCourseDto stu : list){
			if (stu.getTrain() != null){
				stu.setTestTrainNames(stu.getTrain().get("testTrainNames"));
				stu.setTrainNames(stu.getTrain().get("trainNames"));
				stu.setTrain(null);
			}
		}
		PageInfo<StuCourseDto> pageInfo = new PageInfo<>(list);
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	@Override
	@Transactional(readOnly=true)
	public StuCourseDetailDto getStuCourse(Map<String, Object> map) throws Exception  {
		//示例数据
//		String redisKey = RedisKeyConstant.SPORTS + "getStuCourse:"+map;
//		String json = "{\"id\":506,\"detectId\":1062,\"courseSeq\":0,\"name\":\"敏捷\",\"courseTime\":45,\"attenStatus\":1,\"teacherName\":\"刘志鹏\",\"gradeName\":\"一年级\",\"className\":\"测试班\",\"studentName\":\"周海俊\",\"beginTime\":1660790521000,\"endTime\":1660790525000,\"sportStatus\":2,\"avgHeartRate\":77,\"highHeartRate\":86,\"lowHeartRate\":71,\"sportDensity\":0.0,\"train\":null,\"documentIds\":57,\"document\":{\"id\":294,\"orgId\":1,\"outline\":\"单摇双脚\",\"teachAim\":\"1、了解跳绳，学会跳绳；锻练平衡性、协调性。\\n2、监测学生心率状态\",\"teachContent\":\"一、教学示范\\n1、学生带上手环，老师打开心率监测。\\n2、老师讲解动作要领，做示范；讲解绳长调整。\\n3、学生自由练习。\\n二、教学步骤与练习方法\\n1、调整好绳长，向前摇绳，绳接触地面，双脚跳起跨过绳，动作由慢到快。\\n2、能掌握跳绳要领节奏后，连贯跳绳，保持连贯性。\\n三、教学要求\\n1、能连贯完成跳绳动作。\\n2、手臂靠近身体，以手腕为轴摇绳。\\n3、脚屈膝弹起，高度保持3-5CM。\\n4、身体轻快，有弹性。\\n5、绳与身体配合，避免绊绳。\\n四、教学规范练习\\n1、老师平台与设备连接。\\n2、老师口令可以跳绳，心情放轻松。\\n3、跳绳过程不要求太好成绩，减少绊脚。\",\"teachSummary\":\"一、老师调出平台数据分析点评。\\n二、讲解技术要点及失误原因。\\n三、布置课后练习。\",\"teachWarm\":\"热身运动\\n1、头部运动\\n2、手腕运动\\n3、肘关节、肩关节运动\\n4、腰部运动\\n5、膝关节动运\\n6、踝关节运动\\n7、弹弓运动\\n8、放松运动\\n9、慢跑\",\"docProject\":\"1,3\",\"docProjectName\":null,\"createUser\":null,\"createTime\":1632382599000,\"docTag\":\"3,4\",\"docTagName\":null,\"gradeIds\":\"16,17,18\",\"gradeNames\":\"七年级,八年级,九年级\"},\"fileIds\":null,\"files\":[{\"id\":2,\"fileName\":\"470cf7ab8bffc4572058bf350a077d90.mp4\",\"fileImg\":\"https://qiniu.childrenonline.cn/1634727929714.mp4?vframe/jpg/offset/1/w/480/h/360\",\"fileUrl\":\"https://qiniu.childrenonline.cn/1634727929714.mp4\"},{\"id\":3,\"fileName\":\"ad5c69e3ed75604bc2a288d5b88a15cd.mp4\",\"fileImg\":\"https://qiniu.childrenonline.cn/1634727933872.mp4?vframe/jpg/offset/1/w/480/h/360\",\"fileUrl\":\"https://qiniu.childrenonline.cn/1634727933872.mp4\"}],\"trains\":[{\"projectKindName\":\"跳绳\",\"excellentRate\":1,\"isManual\":false,\"id\":2349,\"trainType\":3,\"className\":\"九四班\",\"modelType\":1,\"projectKind\":1,\"startTime\":1660790525000,\"endTime\":1660790525000,\"passingRate\":\"1.00\"},{\"projectKindName\":\"跳绳\",\"excellentRate\":1,\"isManual\":false,\"id\":2350,\"trainType\":3,\"className\":\"九四班\",\"modelType\":1,\"projectKind\":1,\"startTime\":1660790525000,\"endTime\":1660790525000,\"passingRate\":\"1.00\"},{\"projectKindName\":\"跳绳\",\"excellentRate\":1,\"isManual\":false,\"id\":2351,\"trainType\":3,\"className\":\"九四班\",\"modelType\":1,\"projectKind\":1,\"startTime\":1660790525000,\"endTime\":1660790525000,\"passingRate\":\"1.00\"},{\"projectKindName\":\"跳绳\",\"excellentRate\":1,\"isManual\":false,\"id\":2352,\"trainType\":3,\"className\":\"九四班\",\"modelType\":1,\"projectKind\":1,\"startTime\":1660790525000,\"endTime\":1660790525000,\"passingRate\":\"1.00\"},{\"projectKindName\":\"跳绳\",\"excellentRate\":1,\"isManual\":false,\"id\":2353,\"trainType\":3,\"className\":\"九四班\",\"modelType\":1,\"projectKind\":1,\"startTime\":1660790525000,\"endTime\":1660790525000,\"passingRate\":\"1.00\"}],\"detectStuChartDto\":{\"warnList\":[{\"studentName\":null,\"projectName\":\"跳绳\",\"createTime\":1660790525000,\"heartRate\":198}],\"projectList\":[{\"projectName\":\"跳绳\",\"startTime\":1660790525000,\"endTime\":1660790525000,\"achievement\":245,\"projectKind\":1,\"sportType\":1,\"avgHeartRate\":95,\"highHeartRate\":155,\"lowHeartRate\":74},{\"projectName\":\"跳绳\",\"startTime\":1660790525000,\"endTime\":1660790525000,\"achievement\":233,\"projectKind\":1,\"sportType\":1,\"avgHeartRate\":106,\"highHeartRate\":155,\"lowHeartRate\":74},{\"projectName\":\"跳绳\",\"startTime\":1660790525000,\"endTime\":1660790525000,\"achievement\":290,\"projectKind\":1,\"sportType\":1,\"avgHeartRate\":108,\"highHeartRate\":155,\"lowHeartRate\":74},{\"projectName\":\"跳绳\",\"startTime\":1660790525000,\"endTime\":1660790525000,\"achievement\":241,\"projectKind\":1,\"sportType\":1,\"avgHeartRate\":104,\"highHeartRate\":198,\"lowHeartRate\":72}],\"chartDtos\":[{\"createTime\":1632382599000,\"avgHeartRate\":77,\"sportDensity\":0},{\"createTime\":1632382599000,\"avgHeartRate\":108,\"sportDensity\":0.33},{\"createTime\":1632382599000,\"avgHeartRate\":84,\"sportDensity\":0.07},{\"createTime\":1632382599000,\"avgHeartRate\":82,\"sportDensity\":0.08},{\"createTime\":1632382599000,\"avgHeartRate\":91,\"sportDensity\":0},{\"createTime\":1632382599000,\"avgHeartRate\":99,\"sportDensity\":0},{\"createTime\":1632382599000,\"avgHeartRate\":97,\"sportDensity\":0.14},{\"createTime\":1632382599000,\"avgHeartRate\":97,\"sportDensity\":0.17},{\"createTime\":1632382599000,\"avgHeartRate\":110,\"sportDensity\":0.38},{\"createTime\":1632382599000,\"avgHeartRate\":130,\"sportDensity\":0.5},{\"createTime\":1632382599000,\"avgHeartRate\":113,\"sportDensity\":0.41},{\"createTime\":1632382599000,\"avgHeartRate\":101,\"sportDensity\":0.15},{\"createTime\":1632382599000,\"avgHeartRate\":105,\"sportDensity\":0.25},{\"createTime\":1632382599000,\"avgHeartRate\":99,\"sportDensity\":0.15},{\"createTime\":1632382599000,\"avgHeartRate\":112,\"sportDensity\":0.18}],\"timeDistributions\":[{\"desc\":\"非运动\",\"index\":1,\"value\":14,\"percentage\":93},{\"desc\":\"热身\",\"index\":2,\"value\":1,\"percentage\":7},{\"desc\":\"燃脂\",\"index\":3,\"value\":0,\"percentage\":0},{\"desc\":\"有氧\",\"index\":4,\"value\":0,\"percentage\":0},{\"desc\":\"无氧\",\"index\":5,\"value\":0,\"percentage\":0},{\"desc\":\"极限\",\"index\":6,\"value\":0,\"percentage\":0}]}}";
//		StuCourseDetailDto dto = JsonUtil.jsonToClass(json,StuCourseDetailDto.class);
//		redisTemplateUtil.set(redisKey,dto);
		String redisKey = RedisKeyConstant.SPORTS + "getStuCourse:"+map;
		StuCourseDetailDto dto = (StuCourseDetailDto)redisTemplateUtil.get(redisKey);
		if (dto == null){
			dto = courseMapper.getStuCourse(map);
			if (dto != null){
				DetectStuChartDto detectStuChartDto = detectService.getStuDetectChartData(dto.getDetectId(), (Long) map.get("studentId"));
				dto.setDetectStuChartDto(detectStuChartDto);
				redisTemplateUtil.set(redisKey,dto);
			}
		}
		return dto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public HlifeTeachCourseDto putCourse(HlifeTeachCourse course) {
		Date currDate = new Date();
		if (course.getId() == null){
			course.setBeginTime(currDate);
			course.setCreateTime(currDate);
			if (courseMapper.insert(course) > 0){
				return BeanUtil.copyProperties(course, HlifeTeachCourseDto.class);
			}
		}else{
			course.setIsFinish(true);
			course.setEndTime(currDate);
			if (courseMapper.update(course) > 0){
				HlifeTeachCourse c = new HlifeTeachCourse();
				c.setId(course.getId());
				HlifeTeachCourseDto dto = courseMapper.findCourse(c);
				if (dto.getDetectId() != null){
					try {
						detectService.cancelDetect(dto.getDetectId());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (dto.getTrains() != null){
					HlifeTeachPlanDetail planDetail = hlifeTeachPlanDetailMapper.getByPrimaryKey(dto.getTeachPlanDetailId());
					if (planDetail != null && ("".equals(planDetail.getPlanContent()) || planDetail.getPlanContent() == null)){
						StringBuilder sb = new StringBuilder();
						for (TrainDto trainDto:dto.getTrains()){
							String kindName = trainDto.getProjectKindName();
							if (kindName != null && !sb.toString().contains(kindName)){
								sb.append(kindName).append(",");
							}
						}
						if (sb.length() > 0){
							sb.deleteCharAt(sb.length() - 1);
						}
						planDetail.setPlanContent(sb.toString());
						dto.setPlanContent(planDetail.getPlanContent());
						hlifeTeachPlanDetailMapper.updatePlanContent(planDetail);
					}
				}
				return dto;
			}
		}
		return null;
	}

	@Override
	@Transactional(readOnly=true)
	public HlifeTeachCourseDto findCourse(HlifeTeachCourse hlifeTeachCourse) {
		return courseMapper.findCourse(hlifeTeachCourse);
	}

	@Override
	public boolean putCourseSummary(Long courseId, String summary) {
		HlifeTeachCourse course = new HlifeTeachCourse();
		course.setId(courseId);
		course.setSummary(summary);
		return courseMapper.putCourseSummary(course) > 0;
	}

	@Override
	@Transactional(readOnly=true)
	public Map<String, Object> getTeacherStatistics(Long orgId, Long teacherId, int projectKind) {
		Map<String, Object> statMap = new HashMap<>();
		//根据项目类型查询项目
		Map<String, Object> params = new HashMap<>();
		params.put("orgId",orgId);
		params.put("teacherId",teacherId);
		params.put("projectKind",projectKind);
		HlifeTrain hlifeTrain = trainMapper.getTeacherLastTrain(params);
		if(null != hlifeTrain)
		{
			Date endDate = hlifeTrain.getTrainDate();
			if(null==endDate)
			{
				endDate = new Date();
			}
			Date beginDate = TimeUtil.getDateAfterMonths(endDate,-2);
			String strBeginDate = TimeUtil.toStringYYYY_MM_DD(beginDate);
			String strEndDate = TimeUtil.toStringYYYY_MM_DD(endDate);
			//成绩分布统计
			params.put("beginDate",strBeginDate);
			params.put("endDate",strEndDate);
			List<Map<String, Object>> distributeList = trainStudentMapper.getTeacherTrainDistributeStat(params);
			if(!distributeList.isEmpty()) {
				if(null==distributeList.get(0)) {
					distributeList = new ArrayList<>();
				}
			}
			statMap.put("beginDate",strBeginDate);
			statMap.put("endDate",strEndDate);
			statMap.put("distributeList", distributeList);
		}
		return statMap;
	}

	@Override
	@Transactional(readOnly=true)
	public PhysicalAnalysisDto getTeacherPhysicalAnalysis(Long orgId, Long classId) {
		String redisKey = RedisKeyConstant.SPORTS +"getTeacherPhysicalAnalysis:"+orgId+"_"+classId;
		//先从redis中查询,查询不到,再从数据库中查询
		PhysicalAnalysisDto dto = (PhysicalAnalysisDto) redisTemplateUtil.get(redisKey);
		if(null!=dto){
			return dto;
		}
		Map<String, Object> params = new HashMap<>();
		params.put("orgId",orgId);
		params.put("classId",classId);
		dto =  trainMapper.getTeacherPhysicalAnalysis(params);
		redisTemplateUtil.set(redisKey,dto,RedisKeyConstant.EXPIRATION_TIME_2_HOUR);
		return dto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean studentsAttend(Long courseId,List<HlifeTeachCourseAttend> attends) {
		if (courseId != null){
			HlifeTeachCourse hlifeTeachCourse = new HlifeTeachCourse();
			hlifeTeachCourse.setId(courseId);
			hlifeTeachCourse = courseMapper.find(hlifeTeachCourse);
			if (hlifeTeachCourse != null){
				courseMapper.delAttendByCourseId(hlifeTeachCourse.getId());
				if (!attends.isEmpty()){
					courseMapper.insertAttendList(attends);
				}
				return true;
			}
		}
		return false;
	}

}
